﻿//-------------
// <copyright file="UnityControllerFactory.cs" company="Uncas">
//     Copyright (c) Ole Lynge Sørensen. All rights reserved.
// </copyright>
//-------------

namespace Uncas.Katas.SimpleMembership.Web
{
    using System;
    using System.Globalization;
    using System.Web.Mvc;
    using System.Web.Routing;
    using Microsoft.Practices.Unity;

    /// <summary>
    /// Unity controller factory.
    /// </summary>
    public class UnityControllerFactory : DefaultControllerFactory
    {
        /// <summary>
        /// The container.
        /// </summary>
        private readonly IUnityContainer container;

        /// <summary>
        /// Initializes a new instance of the <see cref="UnityControllerFactory"/> class.
        /// </summary>
        /// <param name="container">The container.</param>
        public UnityControllerFactory(IUnityContainer container)
        {
            this.container = container;
        }

        /// <summary>
        /// Retrieves the controller instance for the specified request context and controller type.
        /// </summary>
        /// <param name="requestContext">The context of the HTTP request, which includes the HTTP context and route data.</param>
        /// <param name="controllerType">The type of the controller.</param>
        /// <returns>The controller instance.</returns>
        /// <exception cref="T:System.Web.HttpException">
        /// <paramref name="controllerType"/> is null.</exception>
        /// <exception cref="T:System.ArgumentException">
        /// <paramref name="controllerType"/> cannot be assigned.</exception>
        /// <exception cref="T:System.InvalidOperationException">An instance of <paramref name="controllerType"/> cannot be created.</exception>
        protected override IController GetControllerInstance(
            RequestContext requestContext,
            Type controllerType)
        {
            if (controllerType == null)
            {
                throw new ArgumentNullException("controllerType");
            }

            if (!typeof(IController).IsAssignableFrom(controllerType))
            {
                string message = string.Format(
                    CultureInfo.CurrentCulture,
                    "Type requested is not a controller: {0}",
                    controllerType.Name);
                throw new ArgumentException(
                    message,
                    "controllerType");
            }

            return this.container.Resolve(controllerType) as IController;
        }
    }
}